package calculate24.play.common.calculate24;

//二叉树，用来保存操作符和操作数
class OperationTree {
    public char operation;
    public int value;
    public OperationTree left;
    public OperationTree right;

    public OperationTree(char operation, OperationTree left, OperationTree right) {
        this.operation = operation;
        this.left = left;
        this.right = right;
        switch (operation) {
            case '+':
                this.value = left.value + right.value;
                break;
            case '-':
                this.value = left.value - right.value;
                break;
            case '*':
                this.value = left.value * right.value;
                break;
            case '/':
                this.value = left.value / right.value;
                break;
        }
    }

    public OperationTree(int number) {
        operation = ' ';
        value = number;
        left = null;
        right = null;
    }

    //递归输出表达式
    public String toString() {
        StringBuilder str = new StringBuilder();
        if (left.operation == ' ') {
            str.append(left.value);
        } else {
            str.append('(').append(left.toString()).append(')');
        }
        str.append(operation);
        if (right.operation == ' ') {
            str.append(right.value);
        } else {
            str.append('(').append(right.toString()).append(')');
        }
        return str.toString();
    }
}
